import multer from 'multer'
import { Request } from 'express'
import path from 'path'
import crypto from 'crypto'

// 配置存储
const storage = multer.diskStorage({
    destination: (req: Request, file: Express.Multer.File, cb) => {
        cb(null, path.join(__dirname, '../../uploads'))
    },
    filename: (req: Request, file: Express.Multer.File, cb) => {
        // 生成随机文件名
        const hash = crypto.createHash('md5')
            .update(file.originalname + Date.now())
            .digest('hex')

        const ext = path.extname(file.originalname)
        cb(null, `${hash}${ext}`)
    }
})

// 文件过滤器
const fileFilter = (req: Request, file: Express.Multer.File, cb: multer.FileFilterCallback) => {
    // 允许的文件类型
    const allowedTypes = [
        'image/jpeg',
        'image/png',
        'image/gif',
        'image/webp',
        'video/mp4',
        'video/webm'
    ]

    if (allowedTypes.includes(file.mimetype)) {
        cb(null, true)
    } else {
        cb(new Error('不支持的文件类型'))
    }
}

// 导出 multer 实例
export const upload = multer({
    storage,
    fileFilter,
    limits: {
        fileSize: 10 * 1024 * 1024 // 10MB
    }
}) 